//Page Object
// 获取应用实例
const app = getApp<IAppOption>()
const { request } = require('../../utils/request')
const { markReg,splitContentForPage,getAudioUrl } = require('../../utils/util')

let _audioContext = null as any

Page({
  data: {
    loading: true,
    recordId: '',
    status: '', // 是否分享过，1为未分享 2为已分享
    shareChannel: 2,
    curTemplateData: {},
    templateList: [],
    firstSwiperCurrentIndex: 0,
    curTemplateCode:'',
    guideVisible: !wx.getStorageSync('hadShowGuide') || true,
    cjFlag: 0
  },
  //options(Object)
  onLoad: function (options) {
    if (options && options.recordId) {
      this.setData(
        {
          recordId: options.recordId,
          shareChannel: options.shareChannel || 2,
          curTemplateCode: options.templateCode,
          cjFlag: Number(options.cjFlag) || 0
        },
        () => {
          this.getTemplateData()
        }
      )
      this.initAudioContext()
      this.hideGuide()
      
    } else {
      wx.showModal({
        content: '记录id不存在',
        confirmText: '返回上一页',
        showCancel: false,
        success: () => {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }
  },
  onHide(){
    this.stopGuideAudio()
  },
  onUnload(){
    this.stopGuideAudio()
  },
  hideGuide(){
    setTimeout(()=>{
      this.setData({
        guideVisible: false
      })
      wx.setStorageSync('hadShowGuide',true)
    },3000)
  },
  stopGuideAudio(){
    if(_audioContext){
      _audioContext.stop()
    }
  },
  playGuideAudio(){
    
    if(_audioContext){
      
      if(_audioContext.paused){
        _audioContext.play()
        console.log('playGuide1Audio')
      }else {
        _audioContext.stop()
        console.log('stopGuide1Audio')
      }
    }
  },
  async initAudioContext(){
    
    let audioSrc = await getAudioUrl('https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/template-guide-more.mp3')

    _audioContext = wx.createInnerAudioContext({
      useWebAudioImplement: true 
    }) as any
    _audioContext.src = audioSrc
    _audioContext.onPlay(()=>{
      console.log('playing')
    })
    this.playGuideAudio()
  },
  mainTouchMove(event: any) {
    event.preventDefault()
    return false
  },
  getTemplateData() {
    console.log('getTemplateData')
    // 获取诗歌模版内容
    request({
      url: `/records/${this.data.recordId}/template-contents`,
      method: 'GET',
      success: (data: any) => {
        // console.log('template-contents data:',data)
        if (data && data.length > 0) {
          data.forEach((item: any) => {
            item.cjFlag = this.data.cjFlag
            item.pageList = splitContentForPage(item,{
              riji_firstPageRowNum:12,
              riji_otherPageRowNum:14,
              shuxin_firstPageRowNum:11,
              shuxin_otherPageRowNum:11,
              shige_firstPageRowNum:8,
              shige_otherPageRowNum:8,
            })
            if(item.templateCode === 'shige'){
              item.contlines = item.content.split('\n').length
            }
          })
          this.setData({
            templateList: data,
            curTemplateData: data[0],
          })
        }
      },
      complete: () => {
        this.setData({
          loading: false
        })
      }
    })
  },

  swiperChange(event: any) {
    let { current } = event.detail
    // console.log('current:',current)
    this.setData({
      firstSwiperCurrentIndex:current,
      curTemplateData: this.data.templateList[current],
    })
  },
  getShareData() {
    let that = this
    let userInfo = wx.getStorageSync('userInfo')
    let userId = (userInfo && userInfo.id) || ''
    return new Promise((resolve) => {
      request({
        url: '/record-share',
        method: 'POST',
        data: {
          recordId: this.data.recordId,
          templateCode: this.data.curTemplateData.templateCode
        },
        success: (data: any) => {
          let title = ''
          let currentTemplateCode = this.data.curTemplateData.templateCode
          if (currentTemplateCode === 'riji') {
            title = '我记了一篇日记，快来看看吧'
          } else if (currentTemplateCode === 'shige') {
            title = '我作了一首诗，快来看看吧'
          } else if (currentTemplateCode === 'shuxin') {
            title = '我写了一封信，快来看看吧'
          }
          if(this.data.cjFlag == 1){
            title = '我写给你的新年贺词，喜欢吗？'
          }

          resolve({
            title: title,
            path:
              '/pages/share/share?inviteUserId=' +
              userId +
              '&shareChannel=' +
              that.data.shareChannel +
              '&id=' +
              data.id
          })
        }
      })
    })
  },
  jumpBackPage() {
    wx.navigateBack({
      delta: 1,
      success: () => {
        
      },
      fail: (error) => {
        console.log('fail error:',error)
      }
    })
  },
  changeToThisTemplate(){
    let curTemplateData = this.data.curTemplateData
   
    request({
      url: `/records/${this.data.recordId}/generate-contents/${curTemplateData.id}`,
      method: 'POST',
      data: {
        recordId: this.data.recordId,
        generateContentId: curTemplateData.id
      },
      success:()=>{
        wx.showToast({
          title:'改写成功'
        })
        this.jumpBackPage()
      }
    })
  },
  onShareAppMessage() {
    return {
      ...app.getDefaultShareData(),
      promise: this.getShareData()
    }
  }
})
